<template>
  <div data-v-uploadvideo123 class="upload-video">
    <div class="main">
      <section class="top">
        <h2
          style="
            font-size: 20px;
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
          "
        >
          发布视频
        </h2>
        <el-upload
          class="upload-demo"
          action="http://127.0.0.1:3000/upload/video"
          :on-change="handleChange"
          :on-remove="fileRemove"
          :file-list="fileList"
          :auto-upload="false"
          accept="video/*"
        >
          <el-button
            :disabled="loading"
            size="small"
            type="primary"
            style="margin-left: 15px"
            >更换视频</el-button
          >
        </el-upload>
        <el-progress
          v-if="fileList[0]"
          :percentage="percentage"
          style="margin-top: 10px"
          color="#67c23a"
        ></el-progress>
      </section>
      <section class="body">
        <el-form
          class="video-form"
          :rules="rules"
          ref="form"
          :model="form"
          label-width="80px"
        >
          <el-form-item label="封面" prop="cover">
            <el-upload
              class="cover-upload"
              action="#"
              :show-file-list="false"
              :on-change="coverChange"
              :auto-upload="false"
              v-model="form.cover"
              accept="image/*"
            >
              <img v-if="uploadCoverUrl" :src="uploadCoverUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" style="width: 300px"></el-input>
          </el-form-item>

          <el-form-item label="分区" prop="region">
            <el-select v-model="form.region" placeholder="请选择分区">
              <el-option label="音乐" :value="0"></el-option>
              <el-option label="游戏" :value="1"></el-option>
              <el-option label="动漫" :value="2"></el-option>
              <el-option label="生活" :value="3"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="简介" prop="desc">
            <el-input type="textarea" v-model="form.desc" rows="4"></el-input>
          </el-form-item>

          <el-form-item label="定时发布" prop="timing">
            <el-switch
              style="margin-right: 15px"
              v-model="switchDate"
              @change="changeSwitch"
            >
            </el-switch>
            <el-date-picker
              v-show="switchDate"
              v-model="form.timing"
              type="datetime"
              placeholder="选择日期时间"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button
              :disabled="loading"
              type="primary"
              @click="onSubmit('form')"
            >
              <i v-if="!loading" style="font-style: normal">立即投稿</i>
              <i v-else style="font-style: normal">
                <i class="el-icon-loading"></i> loading</i
              >
            </el-button>
          </el-form-item>
        </el-form>
      </section>
    </div>
  </div>
</template>


<script>
import { putObject, continuinglyTransferring } from "@/upload.js";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
dayjs.extend(relativeTime);

export default {
  name: "UploadVideo",
  data: function () {
    return {
      fileList: [],
      loading: false,
      percentage: 0,

      form: {
        title: "",
        region: "",
        desc: "",
        timing: null,
      },

      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        region: [{ required: true, message: "请选择分区", trigger: "change" }],
        desc: [
          { required: true, message: "请输入简介", trigger: "blur" },
          {
            min: 10,
            max: 500,
            message: "长度在 10 到 500 个字符",
            trigger: "blur",
          },
        ],
      },

      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 如果没有后面的-8.64e7就是不可以选择今天的
        },

        selectableRange: `${dayjs().format("HH:mm:ss")}-23:59:59`,
      },

      switchDate: false,

      credentials: "",

      uploadVideoUrl: "",
      uploadCoverUrl: "",

      newfileList: [],
    };
  },

  created() {
    this.fileList = this.$parent.$data.uploadFile;
    // console.log(this.fileList[0].raw);
    if (this.fileList[0]) {
      this.uploadFile(this.fileList[0].raw);
    }
  },

  methods: {
    async onSubmit(formName) {
      // console.log(this.fileUrl);
      if (!this.uploadVideoUrl || this.uploadVideoUrl === "") {
        return this.$notify({
          title: "警告",
          message: "请先上传视频",
          type: "warning",
        });
      } else if (!this.uploadCoverUrl || this.uploadCoverUrl === "") {
        return this.$notify({
          title: "警告",
          message: "请先上传封面",
          type: "warning",
        });
      }

      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let uploadform = {
            video: this.uploadVideoUrl,
            cover: this.uploadCoverUrl,
            title: this.form.title,
            region: this.form.region,
            video_desc: this.form.desc,
            timing: this.form.timing,
          };

          this.loading = true;

          this.axios
            .post(`upload/video`, uploadform)
            .then((response) => {
              if (response.data.status === 200) {
                // console.log(response);

                const clear = () => {
                  this.loading = false;

                  this.fileList = [];
                  this.uploadVideoUrl = "";
                  this.uploadCoverUrl = "";

                  this.form = {
                    title: "",
                    region: "",
                    desc: "",
                    timing: null,
                  };

                  this.percentage = 0;
                };

                this.$message({
                  message: "投稿成功！",
                  type: "success",
                });

                clear();
              } else {
                console.log(response.data.msg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    },

    // 未使用断点续传
    // onSubmit(formName) {
    //   // console.log(typeof this.form.timing, this.form.timing);

    //   if (!this.fileList[0]) {
    //     return this.$notify({
    //       title: "警告",
    //       message: "请先上传视频",
    //       type: "warning",
    //     });
    //   }

    //   this.$refs[formName].validate((valid) => {
    //     if (valid) {
    //       var form = new FormData();
    //       form.append("video", this.fileList[0].raw);
    //       form.append("cover", this.form.cover.raw);
    //       form.append("title", this.form.title);
    //       form.append("region", this.form.region);
    //       form.append("desc", this.form.desc);
    //       form.append("timing", this.form.timing);

    //       this.axios
    //         .post(`upload/video`, form)
    //         .then((response) => {
    //           if (response.data.status === 200) {
    //             // this.$router.push({ path: "/" });
    //             console.log(response);
    //           } else {
    //             console.log(response.data.msg);
    //           }
    //         })
    //         .catch((err) => {
    //           console.log(err);
    //         });
    //     } else {
    //       return false;
    //     }
    //   });
    // },

    async fileRemove(file, fileList) {
      this.fileList = [];
      // console.log(this.fileList);
    },

    async handleChange(file, fileList) {
      this.fileList = fileList.slice(-1);

      // 清空进度条
      this.percentage = 0;

      // console.log(file.raw);
      this.uploadFile(file.raw);
    },

    // 上传封面
    async coverChange(file, fileList) {
      let result = await putObject(file.raw, "uploads/cover").then((data) => {
        return data;
      });

      this.uploadCoverUrl = result.url;
    },

    async changeSwitch() {
      // console.log(this.switchDate);
      if (!this.switchDate) {
        this.form.timing = null;
      }
    },

    /**
     * @description: 上传视频
     * @param {*} file
     * @return {*} 包含视频地址的对象
     */

    async uploadFile(file) {
      if (!file) return;

      const onProgress = (percentage) => {
        this.percentage = percentage;
      };

      this.loading = true;

      await continuinglyTransferring(file, "uploads/video", onProgress).then(
        (response) => {
          this.loading = false;
          this.uploadVideoUrl = response.url;
        }
      );
    },

    async upVideo() {
      let fileList = [];
      let res = [];

      fileList.forEach(async (value, index) => {
        let result = await putObject(value, "uploads/video").then((data) => {
          return data;
        });

        console.log(`result${index}`, result);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.upload-video[data-v-uploadvideo123] {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;
  //   background-color: red;

  .main {
    width: 85%;
    margin-top: 25px;
    padding: 15px 10px;

    .top {
      width: 100%;
      padding: 15px 10px;
      margin-bottom: 20px;
      background-color: #fff;

      .upload-demo {
        display: flex;
        align-items: center;
        flex-direction: row-reverse;
      }

      .upload-demo::after {
        display: block;
        content: "";
        width: 50px;
        height: 50px;
        margin-right: 10px;
        background-image: url("../../assets/icon/file.png");
        background-position: center;
        background-size: 100%;
        background-repeat: no-repeat;
      }
    }

    .body {
      width: 100%;
      padding: 15px 10px;
      background-color: #fff;

      .video-form {
        .cover-box {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 150px;
          height: 150px;
          font-size: 30px;
          color: #eee;
          border: 1px solid #eee;
        }
      }
    }
  }
}
</style>

<style lang="scss">
.upload-video[data-v-uploadvideo123] {
  .el-upload-list {
    width: 100%;

    .el-upload-list__item:first-child {
      margin-top: 5px;
    }
  }

  .el-upload {
    display: flex;
    align-items: center;
    margin-right: 15px;
  }

  .el-form-item {
    width: 700px;

    .cover-upload {
      width: 320px;
      height: 180px;

      .el-upload {
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100%;
        height: 100%;
        line-height: 178px;
        text-align: center;
      }
      .avatar {
        width: 320px;
        height: 180px;
        display: block;
      }
    }
  }
}
</style>